import 'package:flutter/material.dart';

class WillPopScopeDemo extends StatelessWidget {
  const WillPopScopeDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('导航返回拦截'),
      ),
      body: const WillPopScopeTestRoute(),
    );
  }
}

class WillPopScopeTestRoute extends StatefulWidget {
  const WillPopScopeTestRoute({super.key});

  @override
  WillPopScopeTestRouteState createState() {
    return WillPopScopeTestRouteState();
  }
}

class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> {
  DateTime? _lastPressedAt; //上次点击时间

  @override
  Widget build(BuildContext context) {
    return PopScope(
      onPopInvokedWithResult: (didPop, result) async {
        print(didPop);
        if (didPop) {
          print('1');
          // 返回键被拦截
          final now = DateTime.now();
          //两次返回按钮点击时间间隔超过1秒则重新计时
          if (_lastPressedAt == null || now.difference(_lastPressedAt!) > const Duration(seconds: 1)) {
            _lastPressedAt = now;
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('再按一次退出')));
          } else {
            //退出
            Navigator.of(context).pop(result);
          }
        }
        print('2');
      },
      child: Container(
        alignment: Alignment.center,
        child: const Text("1秒内连续按两次返回键退出"),
      ),
    );
  }
}
